package org.iartisan.wechatsdk

import org.iartisan.runtime.utils.HttpRequestUtil
import org.iartisan.wechatsdk.common.GlobalCache
import org.iartisan.wechatsdk.common.res.{WechatAccessTokenRes, WechatResError}


/**
  * 获取access_token
  *
  * @author King  2019/5/28
  */
object JAccessToken extends LogAspect {

  val accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"

  def getAccessToken(appid:String,secret:String) = {
    val res = HttpRequestUtil.sendGet(String.format(accessTokenURL,appid,secret))
    //解析返回结果
    val error = Option(WechatGsonBuilder.create.fromJson(res, classOf[WechatResError]))
    log.info(s"===>获取微信access_token,appid:$appid,secret$secret")
    //如果没有解析出来errorcode 则请求是成功的
    error.get.getErrcode match {
      case 0 =>
        val accessToken = WechatGsonBuilder.create.fromJson(res, classOf[WechatAccessTokenRes])
        //解析出来accessToken放到全局缓存中
        GlobalCache.putAccessToken(appid, accessToken.getAccessToken)
        accessToken.getAccessToken
      case _ => log.info(s"===>Wechat 返回错误信息${error.get.getErrcode},${error.get.getErrmsg}")
        ""
    }
  }

  def main(args: Array[String]): Unit = {
    println(getAccessToken("aa", ""))
  }
}
